package com.andy.beans.validator;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.beans.factory.annotation.Autowired;

import com.andy.basics.MessageHandler;

public class UniqueValidator implements ConstraintValidator<Unique, String> {

	@PersistenceContext
	private EntityManager entityManager;

	private MessageHandler messageHandler;

	private String model;

	private String field;

	private String message;

	public EntityManager getEntityManager() {
		return this.entityManager;
	}

	public void initialize(final Unique constraintAnnotation) {
		// TODO Auto-generated method stub
		this.model = constraintAnnotation.model();
		this.field = constraintAnnotation.field();
		this.message = constraintAnnotation.message();
	}

	public boolean isValid(final String value, final ConstraintValidatorContext context) {

		if (this.entityManager == null) {
			this.messageHandler.addMessage("entityManager", "Entity Manager is not set !");
			return false;
		}

		List<?> list = this.entityManager.createQuery("from " + this.model + " where " + this.field + "='" + value + "'")
				.getResultList();

		if (list.size() > 0) {
			this.messageHandler.addMessage(this.field, this.message);
			return false;
		}
		return true;
	}

	@Autowired
	public void setMessageHandler(final MessageHandler messageHandler) {
		this.messageHandler = messageHandler;
	}

}
